<template>
	<view class="monitor-page">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="title">仓库视频监控系统</view>
			<view class="operate-btns">
				<button @click="refreshMonitors" class="btn-refresh">
					<uni-icons type="refresh" size="24" color="white"></uni-icons>
					<text>刷新</text>
				</button>
				<button @click="openFullScreen" class="btn-fullscreen">
					<uni-icons type="map" size="24" color="white"></uni-icons>
					<text>全屏</text>
				</button>
			</view>
		</view>

		<!-- 监控区域筛选 -->
		<view class="filter-bar">
			<picker @change="onWarehouseChange" :value="warehouseIndex" :range="warehouseList" range-key="storeName" class="warehouse-picker">
				<view class="picker-text">{{ warehouseList[warehouseIndex]?.name || '选择仓库' }}</view>
			</picker>

			<picker @change="onAreaChange" :value="areaIndex" :range="areaList" range-key="name" class="area-picker">
				<view class="picker-text">{{ areaList[areaIndex]?.name || '选择区域' }}</view>
			</picker>

			<button @click="toggleMode" class="mode-btn" :class="{ active: isPlaybackMode }">
				{{ isPlaybackMode ? '切换到实时' : '切换到回放' }}
			</button>
		</view>

		<!-- 实时监控/回放区域 -->
		<view class="monitor-container">
			<view class="" id="mainCamera"></view>
		</view>
		<!-- 子监控列表（缩略图） -->
		<view class="sub-monitors" v-if="subCameras.length > 0">
			<view class="sub-title">
				<text>其他监控点</text>
				<text class="count">({{ subCameras.length }})</text>
			</view>

			<view class="sub-grid">
				<view
					v-for="(camera, index) in filteredCarmera"
					:key="camera.channelId"
					class="sub-monitor"
					@click="switchMainMonitor(camera)"
					:class="{ active: camera.channelId === mainCamera?.channelId }"
					:id="`camera.channelId`"
				>
					<view class="sub-video" :id="`${camera.channelId}`">
						  <text>{{ camera.channelName }}</text>
				        <view class="sub_btn_box">
							<view class="sub_btn" @click="play.stop(item)">预览</view>
							<view class="sub_btn" @click="stop.stop(item)">停止</view>
						</view>
					</view>
						
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { EZUIKitPlayer } from 'ezuikit-js';
const hikVidos = uniCloud.importObject('hikVidos');

export default {
	name: 'Monitor',
	data() {
		return {
			// 摄像头数据
			cameras: [],
			mainCamera: null, // 主监控摄像头
			subCameras: [], // 子监控摄像头
			players: {}, // 存储播放器实例 { channelId: 实例 }
            warehouseId:'',
			// 仓库筛选
			warehouseList: [],
			warehouseIndex: 0,
          selectedChannelName:'',
			// 区域筛选
			areaList: [
				{ id: 1, name: '全部区域' },
				{ id: 2, name: '入库区' },
				{ id: 3, name: '出库区' },
				{ id: 4, name: '存储区A' },
				{ id: 5, name: '存储区B' }
			],
			areaIndex: 0,

			access_token: ''
		};
	},
     computed:{
		 filteredCarmera(){
			 if(this.selectedChannelName===''){
				 return this.cameras
			 }
		return	 this.cameras?.filter((item)=>item?.channelName===this.selectedChannelName)
		 ||[]}
	 },
	async mounted() {
		// 先获取令牌，再加载摄像头列表
		await this.getToken();
		this.getStroe()
	},

	beforeDestroy() {
		// 组件销毁时停止所有播放器
		Object.values(this.players).forEach((player) => {
			player.stop();
		});
		this.players = {};
	},

	methods: {
		async getStroe(){
			const res=await hikVidos.getStoreList(1,30,'65201')
			this.warehouseList=res.data.rows
			console.log("555",res);
		},
		
		
		/**
		 * 获取访问令牌
		 */
		
		async getToken() {
			try {
				const res = await hikVidos.getVideoToken();
				console.log('获取令牌结果:', res);

				if (res.code === 200 && res.data?.token) {
					this.access_token = res.data.token;
				} else {
					uni.showModal({
						title: '权限错误',
						content: res.errMsg || '获取监控权限失败，请联系管理员'
					});
				}
			} catch (e) {
				console.error('获取令牌异常:', e);
				uni.showModal({
					title: '网络错误',
					content: '获取权限时发生错误，请重试'
				});
			}
		},

		/**
		 * 获取摄像头列表
		 */
		async getCameraList() {
			try {
				const res = await hikVidos.getCameraList(this.warehouseId, 1, 30);
				console.log('摄像头列表结果:', res);
			      this.areaList=res.data.rows.map(item=>item.channelName)

				if (res.code === 200 && res.data?.rows && res.data.rows.length > 0) {
					this.cameras = res.data.rows;
					// 初始化主摄像头和子摄像头
					this.mainCamera = { ...this.filteredCarmera[0], domId: 'mainCamera', loading: false, connected: true };
					this.subCameras = this.filteredCarmera.slice(1).map((cam) => ({
						...cam,
						loading: true,
						connected: false
					}));

					this.initPlay(this.mainCamera);
					// // // 初始化子摄像头预览（可选，根据性能决定）
					//this.initSubCameras();
				} else {
					uni.showModal({
						title: '数据为空',
						content: '未获取到监控设备，请检查配置'
					});
				}
			} catch (e) {
				console.error('获取摄像头列表异常:', e);
				uni.showModal({
					title: '网络错误',
					content: '获取监控设备时发生错误，请重试'
				});
			}
		},

		/**
		 * 初始化子摄像头预览
		 */
		initSubCameras() {
			// 限制同时初始化的子摄像头数量，避免性能问题

			this.subCameras.forEach((camera) => {
				this.initPlay(camera);
			});
		},

		/**
		 * 初始化播放器
		 * @param {Object} camera 摄像头信息
		 */
		initPlay(camera) {
			// 首先检查 camera 是否存在
			if (!camera) {
				console.error('初始化播放器失败：camera 对象不存在');
				return;
			}
			var domId = '';
			var size = { width: 160, height: 90 };
			if (camera.domId) {
				domId = camera.domId;
				size.width = 800;
				size.height = 450;
			} else {
				domId = camera.channelId;
			}

			// 检查必要参数
			if (!this.access_token || !camera.channelId) {
				console.error('初始化播放器失败：缺少必要参数');
				camera.loading = false;
				camera.connected = false;
				return;
			}

			this.$nextTick(() => {
				const player = new EZUIKitPlayer({
					id: domId,
					accessToken: this.access_token,
					url: `ezopen://open.ys7.com/${camera.deviceSerial}/${camera.channelNo}.live`,
					template: 'pcLive',
					quality: 2, // 清晰度：1-流畅，2-高清，3-超清
					talkChannelNo: 1,
					width: size.width,
					height: size.height,
					autoPlay: true,
					audio: false, // 子摄像头默认静音
					download: true,
					downloadRecord: true,
					handleError: (err) => {
						console.error(`摄像头[${camera.name}]错误:`, err);
						camera.loading = false;
						camera.connected = true;
					}
				});
				this.players[camera.channelId] = player;
				this.players[camera.channelId].play();
			});
			// 存储播放器实例
		},

		/**
		 * 切换主监控摄像头
		 * @param {Object} newCamera 新的主摄像头
		 */
		switchMainMonitor(newCamera) {
			// 加强空值检查
			if (!newCamera || !newCamera.channelId || newCamera.channelId === this.mainCamera?.channelId) return;

			const mainToSub = { ...this.mainCamera, domId: null };
			this.mainCamera = { ...newCamera, domId: 'mainCamera', loading: true };

			// 保存当前主摄像头到子摄像头列表
			this.subCameras.push(mainToSub);

			// 从子摄像头列表移除新主摄像头
			this.subCameras = this.subCameras.filter((cam) => cam.channelId !== newCamera.channelId);

			// 确保传入有效的 camera 对象
			if (this.mainCamera) {
				this.initPlay(this.mainCamera);
			}

		},

		async refreshMonitors() {
			// 显示加载状态
			if (this.mainCamera) this.mainCamera.loading = true;
			this.subCameras.forEach((cam) => (cam.loading = true));

			// 重新获取数据
			try {
				await this.getCameraList();
				uni.showToast({ title: '刷新成功', icon: 'success', duration: 1000 });
			} catch (e) {
				uni.showToast({ title: '刷新失败', icon: 'none', duration: 1000 });
			}
		},

		/**
		 * 保存图片
		 * @param {String} url 图片地址
		 */
		saveImage(url) {
			// 调用图片保存API（实际项目中需使用uni.saveImageToPhotosAlbum）
			uni.showToast({ title: '图片保存成功', icon: 'success' });
		},

		/**
		 * 仓库筛选变化
		 * @param {Object} e 事件对象
		 */
		onWarehouseChange(e) {
			this.warehouseIndex = e.detail.value;
			this.warehouseId=this.warehouseList[e.detail.value].storeId
			if(Object.keys(this.players).length>0){
			Object.values(this.players).forEach((player) => {
					player.stop();
				});
				this.players = {};
				this.mainCamera=null
			}
			this.getCameraList()	
		
		},

		/**
		 * 区域筛选变化
		 * @param {Object} e 事件对象
		 */
		onAreaChange(e) {
			this.areaIndex = e.detail.value;
			this.selectedChannelName=this.areaList[e.detail.value]
			// 实际项目中添加筛选逻辑
		},
		play(item){
			console.log("1111",item);
			const camara={...item,domId:""}
			this.initPlay(camara)
		},
		stop(){
			
		},
		

		/**
		 * 回放日期变更
		 * @param {Object} e 事件对象
		 */
		onDateChange(e) {
			this.playbackDate = e.detail.value;
		},

		/**
		 * 开始时间变更
		 * @param {Object} e 事件对象
		 */
		onStartTimeChange(e) {
			this.startTime = e.detail.value;
		},

		/**
		 * 结束时间变更
		 * @param {Object} e 事件对象
		 */
		onEndTimeChange(e) {
			this.endTime = e.detail.value;
		},

		/**
		 * 回放进度变更
		 * @param {Object} e 事件对象
		 */
		onProgressChange(e) {
			this.playbackProgress = e.detail.value;
		},

		/**
		 * 格式化日期
		 * @param {Date} date 日期对象
		 * @returns {String} 格式化后的日期
		 */
		formatDate(date) {
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		},

		/**
		 * 格式化日期时间
		 * @param {Date} date 日期对象
		 * @returns {String} 格式化后的日期时间
		 */
		formatDateTime(date) {
			const time = date.toTimeString().slice(0, 8);
			return `${this.formatDate(date)} ${time}`;
		},

		/**
		 * 格式化回放进度时间
		 * @param {Number} progress 进度值(0-100)
		 * @returns {String} 格式化后的时间
		 */
		formatTime(progress) {
			const totalMinutes = 120; // 2小时录像
			const currentMinute = Math.floor((progress / 100) * totalMinutes);
			const hour = Math.floor(currentMinute / 60)
				.toString()
				.padStart(2, '0');
			const minute = (currentMinute % 60).toString().padStart(2, '0');
			return `${hour}:${minute}`;
		}
	}
};
</script>

<style lang="scss" scoped>
.monitor-page {
	background-color: #1a1a1a;
	color: #fff;
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

/* 导航栏样式 */
.navbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 24rpx;
	background-color: #2c2c2c;
	border-bottom: 1px solid #333;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
}

.operate-btns {
	display: flex;
	gap: 16rpx;
}

.btn-refresh,
.btn-fullscreen {
	background-color: #3a3a3a;
	color: #fff;
	padding: 8rpx 26rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	gap: 10rpx;
	display: flex;
	align-items: center;
}

/* 筛选栏样式 */
.filter-bar {
	display: flex;
	gap: 16rpx;
	padding: 16rpx 24rpx;
	background-color: #2c2c2c;
	border-bottom: 1px solid #333;
	flex-wrap: wrap;
}

.warehouse-picker,
.area-picker {
	flex: 1;
	min-width: 200rpx;
}

.mode-btn {
	background-color: #3a3a3a;
	color: #fff;
	padding: 0 20rpx;
	border-radius: 8rpx;
	font-size: 26rpx;
	white-space: nowrap;
}

.mode-btn.active {
	background-color: #007aff;
}

/* 监控区域样式 */
.monitor-container {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 24rpx;
	height: 40%;
}

.main-monitor {
	display: flex;
	background-color: red;
	height: 600rpx;
}

.video-container {
	display: flex;
	width: 100%;
	background-color: #000;
}

/* 子监控列表 */
.sub-monitors {
	width: 100%;
	background-color: #999;
	margin-top: 10px;
	height: 200px;
}

.sub-title {
	font-size: 28rpx;
	margin-bottom: 16rpx;
	display: flex;
	align-items: center;
	gap: 8rpx;
}
.sub-video {
	background-color: #1a1a1a;
	position: relative;
	display: flex;
	width: 160px;
	height: 90px;
}
.sub_btn_box {
	position: absolute;
	top: 50%;
	z-index: 100;
	left: 0;
	display: flex;
	width: 100%;
	align-items: center;
	justify-content: space-evenly;
	
}
.sub_btn {
	display: flex;
	width: 60rpx;
	justify-content: center;
	align-items: center;
	height: 60rpx;
	font-size: 20rpx;
	border-radius: 25rpx;
	background-color: #999;
}
.count {
	font-size: 24rpx;
	color: #999;
	background-color: #3a3a3a;
	padding: 2rpx 12rpx;
	border-radius: 12rpx;
}

.sub-grid {
	display: flex;
	gap: 16rpx;
}

.sub-monitor {
	background-color: #2c2c2c;
	border-radius: 8rpx;
	overflow: hidden;
	cursor: pointer;
	transition: all 0.3s;
}
</style>
